<template>
    <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">

        <textarea ref="editor" :id="tinymceId" class="tinymce-textarea"/>
        <video-picker :stateManager="videoManager" :multiple="false" @submitPicture="onVideoSuccess"></video-picker>
        <image-picker :stateManager="imageManager" :multiple="false" @submitPicture="onImgSuccess"></image-picker>
    </div>
</template>

<script>
    /**
     * docs:
     * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
     */
    import plugins from './plugins'
    import toolbar from './toolbar'
    import load from './dynamicLoadScript'
    import {getToken} from '@/utils/auth'
    import imagePicker from '../imagePicker'

    import videoPicker from '../videoPicker'
    // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
    const tinymceCDN = 'http://travel.huade.yarsenal.com/storage/tinymce/tinymce.min.js'

    export default {
        name: 'Tinymce',
        props: {
            id: {
                type: String,
                default: function () {
                    return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
                }
            },
            value: {
                type: String,
                default: ''
            },
            toolbar: {
                type: Array,
                required: false,
                default() {
                    return []
                }
            },
            menubar: {
                type: String,
                default: 'file edit insert view format table'
            },
            height: {
                type: [Number, String],
                required: false,
                default: 360
            },
            width: {
                type: [Number, String],
                required: false,
                default: 'auto'
            }
        },
        components: {
            videoPicker,
            imagePicker
        },
        data() {
            return {
                headers: {'Authorization': 'Bearer ' + getToken()},
                hasChange: false,
                hasInit: false,
                percent: 0,
                loading: false,
                tinymceId: this.id,
                fullscreen: false,
                imageManager: {
                    DialogVisible: false
                },
                videoManager: {
                    DialogVisible: false
                },
                languageTypeList: {
                    'en': 'en',
                    'zh': 'zh_CN',
                    'es': 'es_MX',
                    'ja': 'ja'
                }
            }
        },
        computed: {
            containerWidth() {
                const width = this.width
                if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
                    return `${width}px`
                }
                return width
            }
        },
        mounted() {
            this.init()
        },
        activated() {
            if (window.tinymce) {
                this.initTinymce()
            }
        },
        deactivated() {
            this.destroyTinymce()
        },
        destroyed() {
            this.destroyTinymce()
        },
        watch: {
            value(val) {
                if (!this.hasChange && this.hasInit) {
                    this.$nextTick(() =>
                        window.tinymce.get(this.tinymceId).setContent(val || ''))

                }
            }
        },
        methods: {
            init() {
                // dynamic load tinymce from cdn
                load(tinymceCDN, (err) => {
                    if (err) {
                        this.$message.error(err.message)
                        return
                    }
                    this.initTinymce()
                })
            },
            initTinymce() {
                const _this = this
                window.tinymce.init({
                    selector: `#${this.tinymceId}`,
                    language: this.languageTypeList['zh'],
                    height: this.height,
                    body_class: 'panel-body ',
                    object_resizing: false,
                    toolbar: toolbar,
                    menubar: this.menubar,
                    paste_word_valid_elements: '*[*]',        // word需要它
                    paste_data_images: false,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
                    paste_convert_word_fake_lists: false,     // 插入word文档需要该属性
                    paste_webkit_styles: 'all',
                    paste_merge_formats: true,
                    fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
                    plugins: plugins,
                    end_container_on_empty_block: true,
                    powerpaste_word_import: 'clean',
                    code_dialog_height: 450,
                    code_dialog_width: 1000,
                    advlist_bullet_styles: 'square',
                    advlist_number_styles: 'default',
                    default_link_target: '_blank',
                    link_title: false,
                    convert_urls:false,
                    nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                    setup(editor) {
                        _this.hasInit = true
                        editor.on(
                            'init', () => {
                                _this.$emit('on-ready')   // 抛出 'on-ready' 事件钩子
                                editor.setContent(_this.value)
                            }
                        )
                        editor.on('input change undo redo', () => {
                            _this.hasChange = true
                            _this.$emit('input',editor.getContent({ format: 'raw' }))
                        })
                        editor.on('FullscreenStateChanged', (e) => {
                            _this.fullscreen = e.state
                        })
                        editor.ui.registry.addButton('imgUpload', {
                            icon: 'image',
                            onAction: function () {
                                _this.imageManager.DialogVisible = true
                            },
                        })
                        editor.ui.registry.addButton('mediaUpload', {
                            icon: 'media',
                            onAction: function () {
                                _this.videoManager.DialogVisible = true
                            },
                        })
                    },
                })
            },
            onVideoSuccess(e) {
                let self = this
                let value = e.listthumbs[0]
                let ht = `<source src="${value}" type="video/mp4">`
                window.tinymce.get(self.tinymceId).insertContent(`<img class="mce-object mce-object-video" src=""
 width="500" height="400" data-mce-p-controls="controls" data-mce-html="${encodeURI(ht)}" data-mce-object="video">`)
            },
            onImgSuccess(e) {
                let self = this
                let value = e.listthumbs[0]
                console.log(value)
                let imgTag = `<p><img src="${encodeURI(value)}" data-mce-src="${encodeURI(value)}"  /></p>`;
                window.tinymce.get(self.tinymceId).execCommand('mceReplaceContent',false,imgTag)
            },
            destroyTinymce() {
                const tinymce = window.tinymce.get(this.tinymceId)
                if (this.fullscreen) {
                    tinymce.execCommand('mceFullScreen')
                }

                if (tinymce) {
                    tinymce.destroy()
                }
            },
            setContent(value) {
                window.tinymce.get(this.tinymceId).setContent(value)
            },
            getContent() {
                window.tinymce.get(this.tinymceId).getContent()
            },
            imageSuccessCBK(arr) {
                const _this = this
                arr.forEach(v => {
                    window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
                })
            }
        }
    }
</script>

<style scoped>
    .tinymce-container {
        position: relative;
        line-height: normal;
    }

    .tinymce-container >>> .mce-fullscreen {
        z-index: 10000;
    }

    .tinymce-textarea {
        visibility: hidden;
        z-index: -1;
    }

    .editor-custom-btn-container {
        position: absolute;
        right: 4px;
        top: 4px;
        /*z-index: 2005;*/
    }

    .fullscreen .editor-custom-btn-container {
        z-index: 10000;
        position: fixed;
    }

    .editor-upload-btn {
        display: inline-block;
    }
</style>
